<script setup>
import { Edit, Delete } from '@element-plus/icons-vue'
import useUserInfoStore from '@/stores/userInfo.js'
import { ref } from 'vue'
import throttle from 'lodash/throttle'
useUserInfoStore()
//学生提交的作业
const categorys = ref([
  {
    id: 3,
    categoryName: '大数据',
    categoryAlias: '后端',
    createTime: '2023-09-02 12:06:59',
    updateTime: '2023-09-02 12:06:59'
  },
  {
    id: 4,
    categoryName: 'web开发',
    categoryAlias: '前端',
    createTime: '2023-09-02 12:08:16',
    updateTime: '2023-09-02 12:08:16'
  },
  {
    id: 5,
    categoryName: '软件工程',
    categoryAlias: '前后端',
    createTime: '2023-09-02 12:08:33',
    updateTime: '2023-09-02 12:08:33'
  }
])

//用户搜索时选中的分类id
const categoryId = ref('')

//用户搜索时选中的发布状态
const state = ref('')

const subjects = ref([
  {
    id: 5,
    title: '大数据',
    content: '',
    coverImg: '',
    state: '草稿',
    categoryId: 1,
    createTime: '2023-09-03 11:55:30',
    updateTime: '2023-09-03 11:55:30'
  },
  {
    id: 5,
    title: 'web开发',
    content: '',
    coverImg: '',
    state: '草稿',
    categoryId: 2,
    createTime: '2023-09-03 11:55:30',
    updateTime: '2023-09-03 11:55:30'
  },
  {
    id: 5,
    title: '软件工程',
    content: '',
    coverImg: '',
    state: '草稿',
    categoryId: 3,
    createTime: '2023-09-03 11:55:30',
    updateTime: '2023-09-03 11:55:30'
  }
])

//分页条数据模型
const pageNum = ref(1) //当前页
const total = ref(20) //总条数
const pageSize = ref(3) //每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = size => {
  pageSize.value = size
  subjectHomeworkList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = num => {
  pageNum.value = num
  subjectHomeworkList()
}

//回显课程分类列表
import {
  subjectCategoryListService,
  subjectHomeworkAddService,
  subjectHomeworkListService,
  subjectHomeworkUpdateService,
  subjectHomeworkDeleteService
} from '@/api/subject.js'

const subjectCategoryList = async () => {
  let result = await subjectCategoryListService()
  categorys.value = result.data
}
subjectCategoryList()

//获取作业列表
const subjectHomeworkList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    categoryId: categoryId.value ? categoryId.value : null,
    state: state.value ? state.value : null
  }
  let result = await subjectHomeworkListService(params)
  // 渲染视图
  total.value = result.data.total
  subjects.value = result.data.items

  // 处理数据，给数据模型扩展一个属性categoryName
  for (let i = 0; i < subjects.value.length; i++) {
    let subject = subjects.value[i]
    for (let j = 0; j < categorys.value.length; j++) {
      if (subject.categoryId === categorys.value[j].id) {
        subject.categoryName = categorys.value[j].categoryName
      }
    }

    // 根据作业状态处理成绩字段
    if (subject.state === '草稿') {
      subject.grade = '未提交' // 草稿状态下成绩显示为未提交
    } else if (subject.state === '已提交' && !subject.grade) {
      subject.grade = '未批改' // 已提交状态但没有成绩时显示未批改
    }
  }
}

subjectHomeworkList()

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { Plus } from '@element-plus/icons-vue'
//控制抽屉是否显示
const visibleDrawer = ref(false)
//添加表单数据模型
const subjectModel = ref({
  title: '',
  categoryId: '',
  coverImg: '',
  content: '',
  state: ''
})

const rules = {
  title: [
    { required: true, message: '作业题目不能为空', trigger: 'blur' },
    {
      min: 1,
      max: 50,
      message: '作业题目长度应在1到50字符之间',
      trigger: 'blur'
    }
  ],
  categoryId: [
    { required: true, message: '请选择课程分类', trigger: 'change' }
  ],
  content: [
    { required: true, message: '作业内容不能为空', trigger: 'blur' },
    { max: 1000, message: '作业内容最多1000字', trigger: 'blur' }
  ]
}

//导入token
import { useTokenStore } from '@/stores/token.js'

const tokenStore = useTokenStore()

//上传成功回调函数
const uploadSuccess = res => {
  subjectModel.value.coverImg = res.data
  console.log(res.data)
}

//添加作业
import { ElMessage, ElMessageBox } from 'element-plus'
import ImportDialog from '@/components/ImportDialog.vue'

const addHomework = async state => {
  // 验证作业内容是否为空
  if (!subjectModel.value.content.trim()) {
    ElMessage.error('作业内容不能为空')
    return
  }

  // 验证作业内容字数是否超过1000字
  if (subjectModel.value.content.length > 1000) {
    ElMessage.error('作业内容不能超过1000字')
    return
  }

  // 验证是否选择了课程分类
  if (!subjectModel.value.categoryId) {
    ElMessage.error('请选择课程分类')
    return
  }

  // 设置作业状态为传入的参数（已提交或草稿）
  subjectModel.value.state = state

  try {
    if (state === '已提交') {
      // 调用提交作业的接口
      await subjectHomeworkAddService(subjectModel.value)
      ElMessage.success('作业已提交！')
    } else if (state === '草稿') {
      // 调用保存为草稿的接口
      await subjectHomeworkAddService(subjectModel.value) // 假设接口相同
      ElMessage.success('作业已保存为草稿')
    }
    // 关闭抽屉并刷新作业列表
    visibleDrawer.value = false
    await subjectHomeworkList() // 刷新列表
  } catch {
    ElMessage.error('操作失败，请重试')
  }
}

//删除作业
const deleteSubject = row => {
  ElMessageBox.confirm('你确认要删除该作业内容吗？', '温馨提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(async () => {
      await subjectHomeworkDeleteService(row.id)
      ElMessage({
        type: 'success',
        message: '删除成功!'
      })
      await subjectHomeworkList()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除'
      })
    })
}

const editSubject = throttle(row => {
  if (row.state === '已提交') {
    ElMessageBox.alert('该作业已提交，无法修改！', '提示', {
      confirmButtonText: '确定',
      type: 'warning'
    })
  } else {
    // 填充原作业数据到表单中
    subjectModel.value = { ...row }
    visibleDrawer.value = true // 打开抽屉
  }
}, 1000)

// 修改作业
const updateHomework = async state => {
  if (!subjectModel.value.title.trim()) {
    ElMessage.error('作业标题不能为空')
    return
  }
  if (!subjectModel.value.content.trim()) {
    ElMessage.error('作业内容不能为空')
    return
  }
  if (subjectModel.value.content.length > 1000) {
    ElMessage.error('作业内容不能超过1000字')
    return
  }
  if (!subjectModel.value.categoryId) {
    ElMessage.error('请选择课程分类')
    return
  }

  // 设置作业的状态
  subjectModel.value.state = state

  try {
    // 调用更新作业的接口
    await subjectHomeworkUpdateService(subjectModel.value)
    ElMessage.success('作业已更新！')
    visibleDrawer.value = false
    await subjectHomeworkList() // 刷新作业列表
  } catch {
    ElMessage.error('操作失败，请重试')
  }
}

// 导出作业
const handleExport = () => {
  let baseURL = '/api'
  window.location.href = baseURL + '/subjects/exportExcel' // 跳转到后台导出接口
}

// 导入作业
// 导入相关
const importDialogVisible = ref(false)
let baseURL = '/api'
const importUrl = ref(baseURL + '/subjects/importExcel')
const importTemplateUrl = ref(baseURL + '/subjects/template')
// 上传成功后回调
const handleUploaded = () => {
  subjectHomeworkList() // 刷新作业列表
}
</script>
<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>作业管理</span>
        <div class="extra">
          <el-button type="primary" @click="importDialogVisible = true"
            >导入作业</el-button
          >
          <ImportDialog
            v-model="importDialogVisible"
            :upload-url="importUrl"
            :download-url="importTemplateUrl"
            @uploaded="handleUploaded"
          />
          <el-button type="warning" @click="handleExport">导出作业</el-button>
          <el-button type="primary" @click="visibleDrawer = true"
            >作业提交
          </el-button>
        </div>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="作业管理：">
        <el-select
          placeholder="请选择"
          v-model="categoryId"
          style="width: 150px"
        >
          <el-option
            v-for="c in categorys"
            :key="c.id"
            :label="c.categoryName"
            :value="c.id"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="提交状态：">
        <el-select placeholder="请选择" v-model="state" style="width: 150px">
          <el-option label="已提交" value="已提交"></el-option>
          <el-option label="草稿" value="草稿"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="subjectHomeworkList">搜索</el-button>
        <el-button @click="(categoryId = ''), (state = '')">重置</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="subjects" style="width: 100%">
      <el-table-column
        label="作业标题"
        width="300"
        prop="title"
      ></el-table-column>
      <el-table-column label="所属课程" prop="categoryName"></el-table-column>
      <el-table-column label="提交时间" prop="createTime"></el-table-column>
      <el-table-column label="状态" prop="state"></el-table-column>
      <el-table-column label="成绩" prop="grade">
        <template #default="{ row }">
          <span v-if="row.state === '草稿'">未提交</span>
          <span v-else-if="row.state === '已提交' && !row.grade">未批改</span>
          <span v-else>{{ row.grade }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            :icon="Edit"
            circle
            plain
            type="primary"
            @click="editSubject(row)"
          ></el-button>
          <el-button
            :icon="Delete"
            circle
            plain
            type="danger"
            @click="deleteSubject(row)"
          ></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>

    <!-- 分页条 -->
    <el-pagination
      v-model:current-page="pageNum"
      v-model:page-size="pageSize"
      :page-sizes="[3, 5, 10, 15]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="onCurrentChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 抽屉 -->
    <el-drawer
      v-model="visibleDrawer"
      title="编辑作业"
      direction="rtl"
      size="50%"
    >
      <!-- 添加文章表单 -->
      <el-form :model="subjectModel" label-width="100px" :rules="rules">
        <el-form-item label="作业题目" prop="title">
          <el-input
            v-model="subjectModel.title"
            minlength="1"
            maxlength="10"
            placeholder="请输入作业题目"
          ></el-input>
        </el-form-item>
        <el-form-item label="课程分类">
          <el-select placeholder="请选择" v-model="subjectModel.categoryId">
            <el-option
              v-for="c in categorys"
              :key="c.id"
              :label="c.categoryName"
              :value="c.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="作业图片">
          <!--
               auto-upload:设置是否自动上传
               action:服务器接口路径
               name:上传的文件字段名
               headers:请求头
               on-success:上传成功回调函数

           -->

          <el-upload
            class="avatar-uploader"
            :auto-upload="true"
            :show-file-list="false"
            action="/api/upload"
            name="file"
            :headers="{ Authorization: tokenStore.token }"
            :on-success="uploadSuccess"
          >
            <img
              v-if="subjectModel.coverImg"
              :src="subjectModel.coverImg"
              class="avatar"
              alt=""
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="作业内容" prop="content">
          <div class="editor">
            <quill-editor
              theme="snow"
              v-model:content="subjectModel.content"
              contentType="html"
            >
            </quill-editor>
          </div>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="
              subjectModel.id ? updateHomework('已提交') : addHomework('已提交')
            "
            >提交
          </el-button>
          <el-button
            type="info"
            @click="
              subjectModel.id ? updateHomework('草稿') : addHomework('草稿')
            "
            >草稿
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </el-card>
</template>
<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

/* 抽屉样式 */
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>
